package com.yunyouyi.cpicture.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunyouyi.cpicture.domain.space.service.SpaceDomainService;
import com.yunyouyi.cpicture.infrastructure.exception.BusinessException;
import com.yunyouyi.cpicture.infrastructure.exception.ErrorCode;
import com.yunyouyi.cpicture.infrastructure.exception.ThrowUtils;
import com.yunyouyi.cpicture.interfaces.dto.space.SpaceAddDTO;
import com.yunyouyi.cpicture.interfaces.dto.space.SpaceQueryDTO;
import com.yunyouyi.cpicture.domain.space.entity.Space;
import com.yunyouyi.cpicture.domain.space.entity.SpaceUser;
import com.yunyouyi.cpicture.domain.user.entity.User;
import com.yunyouyi.cpicture.domain.space.valueobject.SpaceLevelEnum;
import com.yunyouyi.cpicture.domain.space.valueobject.SpaceRoleEnum;
import com.yunyouyi.cpicture.domain.space.valueobject.SpaceTypeEnum;
import com.yunyouyi.cpicture.interfaces.vo.space.SpaceVO;
import com.yunyouyi.cpicture.interfaces.vo.user.UserVO;
import com.yunyouyi.cpicture.application.service.SpaceApplicationService;
import com.yunyouyi.cpicture.infrastructure.mapper.SpaceMapper;
import com.yunyouyi.cpicture.application.service.SpaceUserApplicationService;
import com.yunyouyi.cpicture.application.service.UserApplicationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author yunyouyi
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-04-18 09:56:29
*/
@Service
public class SpaceApplicationServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceApplicationService {

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private SpaceUserApplicationService spaceUserApplicationService;

    @Resource
    private SpaceDomainService spaceDomainService;

    /**
     * 添加空间
     * @param spaceAddDTO
     * @param loginUser
     * @return
     */
    public Long addSpace(SpaceAddDTO spaceAddDTO, User loginUser) {
        //TODO 添加空间
        ThrowUtils.throwIf(spaceAddDTO == null, ErrorCode.PARAMS_ERROR,"添加空间失败");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR,"添加空间失败用户未登录");
        String role = loginUser.getUserRole();
        //DTO转化为实体类
        Space space = new Space();
        if(spaceAddDTO.getSpaceName() == null){
            space.setSpaceName("默认空间");
        }
        space.setSpaceName(spaceAddDTO.getSpaceName());
        if(spaceAddDTO.getSpaceLevel() == null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }else {
            space.setSpaceLevel(spaceAddDTO.getSpaceLevel());
        }
        // 设置默认值SpaceType
        if(spaceAddDTO.getSpaceType() == null){
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }else{
            space.setSpaceType(spaceAddDTO.getSpaceType());
        }
        //数据自动填充
        this.fillSpaceBySpaceLevel(space);
        //数据校验
        this.validSpace(space, true);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        //权限校验
        if(SpaceLevelEnum.COMMON.getValue() != spaceAddDTO.getSpaceLevel() && !loginUser.isAdmin()){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有权限创建指定级别空间");
        }
        //控制同一个用户只能有一个空间,和一个团队空间
        String lock = String.valueOf(userId).intern();
        synchronized (lock){
            Long newSpaceId = transactionTemplate.execute(action -> {
                //判断是否已有空间
                boolean isExist = this.lambdaQuery()
                        .eq(Space::getUserId, userId)
                        .eq(Space::getSpaceType, space.getSpaceType())
                        .exists();
                ThrowUtils.throwIf(isExist,ErrorCode.OPERATION_ERROR,"用户已有空间");
                // 写入数据库
                boolean result = this.save(space);
                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                // 如果是团队空间，关联新增团队成员记录
                if (SpaceTypeEnum.TEAM.getValue() == spaceAddDTO.getSpaceType()) {
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(userId);
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    result = spaceUserApplicationService.save(spaceUser);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                }
                // 返回新写入的数据 id
                return space.getId();
            });
            return Optional.ofNullable(newSpaceId).orElse(-1L);//?
        }
    }
    /**
     * 验证空间合法性
     * @param space
     * @param add
     */
    public void validSpace(Space space, boolean add){
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR, "空间为空");
        //空间名以及level
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        Integer spaceType = space.getSpaceType();
        SpaceTypeEnum enumByValue = SpaceTypeEnum.getEnumByValue(spaceType);
        //判断是否是添加
        if(add){
            ThrowUtils.throwIf(StrUtil.isBlank(spaceName), ErrorCode.PARAMS_ERROR,"空间名为空");
            ThrowUtils.throwIf(space.getSpaceLevel() == null, ErrorCode.PARAMS_ERROR,"空间等级为空");
            ThrowUtils.throwIf(spaceType == null, ErrorCode.PARAMS_ERROR,"空间类型为空");
        }
        ThrowUtils.throwIf(spaceLevel != null && spaceLevelEnum == null, ErrorCode.PARAMS_ERROR,"空间等级不存在");
        ThrowUtils.throwIf(StrUtil.isNotBlank(spaceName) && spaceName.length() > 30, ErrorCode.PARAMS_ERROR,"空间名长于30字或者未填写");
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        // 对象转封装类
        SpaceVO spaceVO = SpaceVO.obj2VO(space);
        // 关联查询用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userApplicationService.getUserById(userId);
            UserVO userVO = userApplicationService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream()
                .map(SpaceVO::obj2VO)
                .collect(Collectors.toList());
        // 1. 关联查询用户信息
        // 1,2,3,4
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        // 1 => user1, 2 => user2
        Map<Long, List<User>> userIdUserListMap = userApplicationService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userApplicationService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryDTO spaceQueryDTO) {
        return spaceDomainService.getQueryWrapper(spaceQueryDTO);
    }

    /**
     * 根据空间级别自动填充限额
     * @param space
     */
    public void fillSpaceBySpaceLevel(Space space) {
        spaceDomainService.fillSpaceBySpaceLevel(space);
    }

    /**
     * 权限校验
     * @param loginUser
     * @param space
     */
    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        spaceDomainService.checkSpaceAuth(loginUser, space);
    }
}




